package com.xuexi.demos.controller;

import com.xuexi.demos.entity.ChatMessage;
import com.xuexi.demos.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@MessageMapping("/chat")
public class ChatController {

    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);
    private final SimpMessagingTemplate messagingTemplate;
    public static final Set<String> onlineUsers = ConcurrentHashMap.newKeySet();
    private final Map<String, String> sessionUserMap = new ConcurrentHashMap<>();

    public ChatController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    public static Set<String> getOnlineUsers() {
        return Collections.unmodifiableSet(onlineUsers);
    }

    // 群聊消息
    @MessageMapping("/sendMessage")
    public void sendMessage(@Payload ChatMessage chatMessage) {
        chatMessage.setTimestamp(getTimestamp());
        logger.info("[群聊] {}: {}", chatMessage.getSender(), chatMessage.getContent());
        messagingTemplate.convertAndSend("/topic/public", chatMessage);
    }

    // 用户加入
    @MessageMapping("/addUser")
    public void addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        String username = chatMessage.getSender() != null ? chatMessage.getSender().trim() : "";

        if (username.isEmpty()) return;

        if (onlineUsers.contains(username)) {
            logger.warn("用户名已存在: {}", username);
            messagingTemplate.convertAndSendToUser(
                    username,
                    "/queue/private",
                    new ChatMessage("SYSTEM", "用户名已存在，请换一个！", username, null, null, getTimestamp())
            );
            return;
        }

        onlineUsers.add(username);
        String sessionId = headerAccessor.getSessionId();
        sessionUserMap.put(sessionId, username);
        headerAccessor.getSessionAttributes().put("username", username);

        // 更新数据库用户状态为在线
        userService.updateStatus(username, 1);

        logger.info("用户上线: {} (sessionId={})", username, sessionId);

        // 广播加入通知
        messagingTemplate.convertAndSend(
                "/topic/public",
                new ChatMessage("JOIN", username + " 加入了聊天室", username, null, null, getTimestamp())
        );

        // 更新用户列表
        broadcastUserList();

        // 向自己发送欢迎消息
        messagingTemplate.convertAndSendToUser(
                username,
                "/queue/private",
                new ChatMessage("SYSTEM", "欢迎来到聊天室！", null, username, null, getTimestamp())
        );
    }


    // 私聊消息
    @MessageMapping("/private")
    public void sendPrivate(@Payload ChatMessage chatMessage) {
        String sender = chatMessage.getSender() != null ? chatMessage.getSender().trim() : "";
        String receiver = chatMessage.getReceiver() != null ? chatMessage.getReceiver().trim() : "";

        if (sender.isEmpty() || receiver.isEmpty() || chatMessage.getContent() == null) {
            return;
        }

        chatMessage.setTimestamp(getTimestamp());
        logger.info("[私聊] {} -> {}: {}", sender, receiver, chatMessage.getContent());

        // 发送给接收者
        messagingTemplate.convertAndSendToUser(
                receiver,
                "/queue/private",
                chatMessage
        );

        // 同时发送给自己（保持对话同步）
        messagingTemplate.convertAndSendToUser(
                sender,
                "/queue/private",
                chatMessage
        );
    }

    // 用户断开连接
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        String username = sessionUserMap.get(sessionId);

        if (username == null) {
            username = (String) headers.getSessionAttributes().get("username");
        }

        if (username != null) {
            onlineUsers.remove(username);
            sessionUserMap.values().remove(username);

            // 更新数据库用户状态为离线
            userService.updateStatus(username, 0);

            logger.info("用户下线: {} (sessionId={})", username, sessionId);

            // 广播离开通知
            messagingTemplate.convertAndSend(
                    "/topic/public",
                    new ChatMessage("LEAVE", username + " 离开了聊天室", username, null, null, getTimestamp())
            );

            broadcastUserList();
        }
    }


    // 推送在线用户列表
    private void broadcastUserList() {
        List<String> userList = new ArrayList<>(onlineUsers);
        logger.info("推送在线用户列表: {}", userList);
        messagingTemplate.convertAndSend("/topic/userlist", userList);
    }

    private String getTimestamp() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}